package cn.xsshome.body.imgutil;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * 图像处理工具类
 * @author 小帅丶
 */
public class ImgHandleUtil {
	public static void main(String[] args) throws Exception {
		ImgSimpleMerge("G:/testimg/46.png", "G:/testimg/xcx.jpg", 186, 128, "G:/testimg/merge1027.jpg");
	}
	/**
	 * 图片合成
	 * @param bottomImg  底图
	 * @param layerImg 层图
	 * @param posw 合成的位置x
	 * @param posh 合成的位置y
	 * @param outFile 输出目标图片文件路径
	 * @throws Exception
	 */
	public static void ImgSimpleMerge(String bottomImg,String layerImg,int posw,int posh,String outFile) throws Exception {
		// 获取底图
        BufferedImage bufferedbottomImg = ImageIO.read(new File(bottomImg));
        // 获取层图
        BufferedImage bufferedlayerImg = ImageIO.read(new File(layerImg));
        //合并两个图像
        int bufferedbottomW = bufferedbottomImg.getWidth();
        int bufferedbottomH = bufferedbottomImg.getHeight();
        int bufferedlayerImgW = bufferedlayerImg.getWidth();
        int bufferedlayerImgH = bufferedlayerImg.getHeight();
        
        //创建一个新的内存图像
        BufferedImage imageSaved = new BufferedImage(bufferedbottomW, bufferedbottomH, BufferedImage.TYPE_INT_ARGB);
        
        Graphics2D g2d = imageSaved.createGraphics();
        //绘制背景图像
        g2d.drawImage(bufferedbottomImg, null, 0, 0);  
        
        for (int i = 0; i < bufferedlayerImgW; i++) {
            for (int j = 0; j < bufferedlayerImgH; j++) {
                int bufferedbottomImgRGB = bufferedbottomImg.getRGB(i + posw, j + posh);
                int bufferedlayerImgRGB = bufferedlayerImg.getRGB(i, j);
                imageSaved.setRGB(i + posw, j + posh, bufferedlayerImgRGB); //修改像素值
            }
        }
        ImageIO.write(imageSaved, "png", new File(outFile));
        System.out.println(String.format("图片合成成功，合成图片文件为： %s", outFile));
	}
}
